package com.liuliuliu.payment.globalpaymentspringbootstarter.service.impl;

import com.alibaba.fastjson.JSON;
import com.liuliuliu.payment.globalpaymentspringbootstarter.enums.PaymentChannelEnum;
import com.liuliuliu.payment.globalpaymentspringbootstarter.request.GetPaymentLinkReq;
import com.liuliuliu.payment.globalpaymentspringbootstarter.request.stripe.StripeAccountInfo;
import com.liuliuliu.payment.globalpaymentspringbootstarter.request.stripe.StripePaymentReq;
import com.liuliuliu.payment.globalpaymentspringbootstarter.response.GenPaymentLinkResp;
import com.liuliuliu.payment.globalpaymentspringbootstarter.service.PaymentService;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.Customer;
import com.stripe.model.Price;
import com.stripe.model.Product;
import com.stripe.model.checkout.Session;
import com.stripe.param.CustomerCreateParams;
import com.stripe.param.PriceCreateParams;
import com.stripe.param.ProductCreateParams;
import com.stripe.param.checkout.SessionCreateParams;

import java.util.logging.Logger;


public class StripePaymentService implements PaymentService {

    private static Logger log = Logger.getLogger(StripePaymentService.class.getName());


    @Override
    public PaymentChannelEnum getPaymentChannel() {
        return PaymentChannelEnum.STRIPE;
    }

    public GenPaymentLinkResp genPaymentUrl(GetPaymentLinkReq req) {
        StripePaymentReq stripePaymentReq = JSON.parseObject(
                JSON.toJSONString(req.getParams()), StripePaymentReq.class);

        StripeAccountInfo stripeInfo = JSON.parseObject(JSON.toJSONString(req.getAccountInfo()), StripeAccountInfo.class);

        Stripe.apiKey = stripeInfo.getPrivateKey();
        Session session = null;

        try {
            // 1. 创建 Customer
            CustomerCreateParams createParams = CustomerCreateParams.builder()
                    .setName(stripePaymentReq.getCustomerName())
                    .setEmail(stripePaymentReq.getCustomerEmail())
                    .build();
            Customer customer = Customer.create(createParams);

            // 2. 创建 Product
            ProductCreateParams productParams = ProductCreateParams.builder()
                    .setName(stripePaymentReq.getProductName())
                    .addImage(stripePaymentReq.getProductUrl())
                    .build();
            Product product = Product.create(productParams);

            // 3. 创建 Price（注意金额是最小货币单位，比如美元是美分）
            PriceCreateParams priceParams = PriceCreateParams.builder()
                    .setUnitAmount(Long.valueOf(stripePaymentReq.getAmount())) // 这里要确认 amount 是否传的是分/美分
                    .setCurrency(stripePaymentReq.getCurrency().toLowerCase())
                    .setProduct(product.getId())
                    .build();
            Price price = Price.create(priceParams);

            log.info("Stripe customerId: {}"+customer.getId());
            log.info("Stripe productId: {}"+product.getId());
            log.info("Stripe priceId: {}"+ price.getId());

            // 4. 创建 Checkout Session
            SessionCreateParams.LineItem lineItem = SessionCreateParams.LineItem.builder()
                    .setPrice(price.getId())
                    .setQuantity(1L) // 你可以传 req.getQuantity()
                    .build();

            SessionCreateParams params = SessionCreateParams.builder()
                    .setMode(SessionCreateParams.Mode.PAYMENT)
                    .setSuccessUrl("https://your-domain.com/success?session_id={CHECKOUT_SESSION_ID}")
                    .setCancelUrl("https://your-domain.com/cancel")
                    .setCustomer(customer.getId())
                    .addLineItem(lineItem)
                    .build();
            session =Session.create(params);
            log.info("Stripe checkout sessionId: {}"+ session.getId());
            log.info("Stripe checkout url: {}"+session.getUrl());
        } catch (StripeException e) {
            throw new RuntimeException(e);
        }
        // 5. 封装返回
        return GenPaymentLinkResp.builder().paymentUrl(session.getUrl()).build();
    }

}
